<?php
namespace app\shop\controller;
use app\AdminRest;
use app\shop\model\AdminCompany;
use think\App;
use think\facade\Db;
use think\Request;
use app\shop\model\AdminShopOrder;
class AdminExcel extends AdminRest
{

    protected $order_model;
    public function __construct(App $app) {
        parent::__construct($app);
        $this->order_model = new AdminShopOrder();
    }
    /**
     * User: chenniang
     * Date: 2019-09-10 10:47
     * @return \think\Response
     * descption:phpExcel 导出方法
     */
    function excelExport($fileName = '', $headArr = [], $data = []) {

        require_once  EXTEND_PATH.'PHPExcel/PHPExcel.php';
        ini_set("memory_limit", "1024M"); // 设置php可使用内存
        set_time_limit(30);  # 设置执行时间最大值
        $fileName   .= "_" . date("Y_m_d", time()) . ".xls";
        $objPHPExcel = new \PHPExcel();
        $objWriter   = \PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objPHPExcel->getProperties();
        $key = ord("A"); // 设置表头
        foreach ($headArr as $v) {
            $e=mb_detect_encoding($v, array('UTF-8', 'GBK'));
            if($e!='UTF-8') {
                $v = mb_convert_encoding($v, "UTF-8", "GBK");
            }
            $colum = chr($key);
            $objPHPExcel->setActiveSheetIndex(0)->setCellValue($colum . '1', $v);
            $key += 1;
        }
        $column = 2;
        $objActSheet = $objPHPExcel->getActiveSheet(0);
        foreach ($data as $key => $rows) { // 行写入
            $span = ord("A");
            foreach ($rows as $keyName => $value) { // 列写入
                $e=mb_detect_encoding($value, array('UTF-8', 'GBK'));
                if($e!='UTF-8'){
                    $value = mb_convert_encoding($value, "UTF-8", "GBK");
                }
                $value = $this->filterEmoji($value);
                $objActSheet->setCellValueExplicit(chr($span) . $column, $value);
                $span++;
            }
            $column++;
        }
        ob_end_clean();
        header('Content-Type: application/vnd.ms-excel');
        header("Content-Disposition: attachment;filename=$fileName");
        header('Cache-Control: max-age=0');
        header('content-Type:application/vnd.ms-excel;charset=utf-8');
        $objWriter->save('php://output');// 文件通过浏览器下载
        return $fileName;
        exit();
    }
    /**
     * @param $str
     * @return string|string[]|null
     * 过滤表情包
     */
    public function filterEmoji($str)
    {
        $str = preg_replace_callback(
            '/./u',
            function (array $match) {
                return strlen($match[0]) >= 4 ? '' : $match[0];
            },
            $str);

        return $str;
    }
    /**
     * User: chenniang
     * Date: 2019-09-10 10:46
     * @return \think\Response
     * descption:返回url
     */
    public function returnUrl(){
        $input = $this->_param;
        return $this->success($input['url']);
    }

    /**
     * User: chenniang
     * Date: 2019-09-10 10:46
     * @return \think\Response
     * descption:导出用户订单
     */
    public function orderExcel(){

        $input = $this->_param;

        if(!empty($input['order_status'])){
            $dis = $this->orderStatus($input['order_status']);
        }
        if(!empty($input['transaction_id'])){

            $dis[] = ['a.transaction_id','like','%'.$input['transaction_id']."%"];
        }
        if(!empty($input['order_code'])){

            $dis[] = ['a.out_trade_no','like',"%".$input['order_code']."%"];
        }
        if(!empty($input['name'])){

            $dis[] = ['b.name','like',"%".$input['name']."%"];
        }
        if(!empty($input['phone'])){

            $dis[] = ['a.phone','like',"%".$input['phone']."%"];
        }

        if(!empty($input['start_time'])){

            $start_time = strtotime($input['start_time']. ' 00:00:00');

            $dis[] = ['a.create_time','>=',$start_time];

        }
        if(!empty($input['end_time'])){

            $end_time = strtotime($input['end_time']. ' 23:59:59');

            $dis[] = ['a.create_time','<=',$end_time];
        }

        //自提
        if(!empty($input['is_self'])&&$input['is_self']==1){

            $dis[] = ['a.address_id','=',-1];
        }
        //快递
        if(!empty($input['is_self'])&&$input['is_self']==2){

            $dis[] = ['a.address_id','>',0];
        }

        /**
         * 根据公司部门筛选
         */
        if(!empty($input['company'])){

            $company = $input['company'];

            $company_model = new AdminCompany();

            $cpy_ids = $company_model->companyLow($company);

            array_unshift($cpy_ids,$company);

            $dis[] = ['c.company_id','in',$cpy_ids];
        }

        $dis[] = ['a.uniacid','=',$this->_uniacid];

        $dis[] = ['a.status','>',-1];

        $order = $this->order_model->orderSelect($dis);

        if(!empty($order)){
            foreach ($order as &$value){
                $value['goods_info_text'] = $this->goodsText($value['goods_text']);
            }
        }
        $name  ='订单列表';
        $header=[
            '订单ID',
            '商品名',
            '下单用户id',
            '微信昵称',
            '员工',
            '实收金额',
            '收货地址',
            '下单手机号',
            '支付方式',
            '系统订单号',
            '微信订单号',
            '下单时间',
            '订单类型',
            '状态',
            '核销人',
        ];
        $new_data = [];

        foreach ($order as &$v){
            $info   = array();
            $info[] = $v['id'];
            $info[] = $v['goods_info_text'];
            $info[] = $v['user_id'];
            $info[] = $v['nickname_text'];
            $info[] = $v['staff_text'];
            $info[] = $v['total_price'];
            $info[] = $v['address_text'];
            $info[] = $v['phone'];
            $info[] = $v['stored']>0?'储值支付':'微信支付';
            $info[] = $v['out_trade_no'];
            $info[] = $v['transaction_id'];
            $info[] = $v['create_time']?date('Y-m-d H:i:s',$v['create_time']):'暂无信息';
            $info[] = $v['type']==1?'拼团订单':'普通订单';
            $info[] = $v['status_text'];
            $info[] = $v['hx_user_text'];
            $new_data[] = $info;
        }

        $fileName=$this->excelExport($name,$header,$new_data);
        return $this->success($fileName);
    }


    /**
     * User: chenniang
     * Date: 2019-09-19 11:47
     * @param $type
     * @return array
     * descption:获取订单状态
     */
    public function orderStatus($type){
        switch ( $type ) {
            //  1=>待付款
            case 1:
                $where[] = [ 'a.pay_status','=',0 ];
                $where[] = [ 'a.order_status','=',0 ];
                break;
            //  2=>待发货
            case 2:
                $where[] = [ 'a.pay_status','=',1 ];
                $where[] = [ 'a.order_status','=',0 ];
                break;
            //  3=>待收货
            case 3:
                $where[] = [ 'a.pay_status','=',1 ];
                $where[] = [ 'a.order_status','=',2 ];
                break;
            //  4=>已完成
            case 4:
                $where[] = [ 'a.pay_status','=',1 ];
                $where[] = [ 'a.order_status','>',2 ];
                break;
            //  5=>已取消
            case 5:
                $where[] = [ 'a.order_status','=',1 ];
                break;
            //  0=>全部订单
            default:
        }
        return $where;
    }
    /**
     * 获取商品拼接
     */

    public function goodsText($data){
        $names = '';
        if(is_array($data)){
            foreach ($data as $value){
                $names .=  $value[ 'name' ] . ': ' . $value[ 'content' ] . '，数量：' . $value[ 'number' ].';';
            }
        }
        return $names;
    }






}
